<?php

namespace App\Repositories;

use App\Models\Orders;
use App\Models\ServiceType;
use BobCoder\Construct\Foundation\Repository\Repository;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class OrderRepository extends Repository
{
    protected $model;

    public function __construct()
    {
        $this->model = new Orders();

    }

    /**
     * 订单分页
     * @param int $companyId 公司ID
     * @param int $type 订单类型
     * @param int $pageSize
     * @return LengthAwarePaginator
     * @Author 姿势就是力量
     */
    public function getPageList(int $companyId, string $types, int $status, int $type_name, $type, $passenger, string $order_sn, string $number, string $reality_start, string $reality_end, string $created_at, string $book_time, string $end_time, string $reality_start_time, string $should_price, string $discount_price, string $km, string $minute, string $c_name, string $nick_name, string $mobile, string $real_name, string $driver_money, string $surplus_profit, string $invoice_number, string $cancel_reason, int $pageSize = 10)
    {
        $list = $this->model
            ->company($companyId)
            ->where('status', '!=', '0')
            ->when($type, function ($query) use ($type) {
                if ($type) {
                    $query->where('service_id', $type);
                }
            })
            ->with([
                'corporation:id,name',
                'driver:id,real_name,phone',
                'passenger:id,name,phone,nick_name',
                'car:id,number',
                'distance:id,order_id,book_start,book_end,book_time,reality_start_time,reality_start,reality_end',
                'service_type:id,name',
            ])
            ->when($order_sn, function ($query) use ($order_sn) {
                if ($order_sn) {
                    $query->where('order_sn', 'like', '%' . $order_sn . '%'); //查询订单号
                }
            })
            ->when($status, function ($query) use ($status) {
                if ($status) {
                    $query->where('status', 'like', '%' . $status . '%');       //订单状态
                }
            })
            ->when($type_name, function ($query) use ($type_name) {
                if ($type_name) {
                    $query->where('service_type_id', 'like', '%' . $type_name . '%'); //业务类型
                }
            })
            ->when($created_at, function ($query) use ($created_at) {
                if ($created_at) {
                    $list = explode(',', $created_at);
                    $query->whereBetween('created_at', [$list[0], $list[1]]); //下单时间
                }
            })
            ->when($end_time, function ($query) use ($end_time) {
                if ($end_time) {
                    $list = explode(',', $end_time);
                    $query->whereBetween('end_time', [$list[0], $list[1]]);   //查询结束时间
                }
            })
            ->when($should_price, function ($query) use ($should_price) {
                if ($should_price) {
                    $query->where('should_price', 'like', '%' . $should_price . '%');   //查询应收金额
                }
            })
            ->when($discount_price, function ($query) use ($discount_price) {
                if ($discount_price) {
                    $query->where('discount_price', 'like', '%' . $discount_price . '%');   //查询优惠金额
                }
            })
            ->when($km, function ($query) use ($km) {
                if ($km) {
                    $query->where('km', 'like', '%' . $km . '%');//查询服务里程
                }
            })
            ->when($minute, function ($query) use ($minute) {
                if ($minute) {
                    $query->where('minute', 'like', '%' . $minute . '%');//查询总服务时间
                }
            })
            ->when($driver_money, function ($query) use ($driver_money) {
                if ($driver_money) {
                    $query->where('driver_money', 'like', '%' . $driver_money . '%');//查询司机应得
                }
            })
            ->when($surplus_profit, function ($query) use ($surplus_profit) {
                if ($surplus_profit) {
                    $query->where('surplus_profit', 'like', '%' . $surplus_profit . '%');//查询剩余利润
                }
            })
            ->when($invoice_number, function ($query) use ($invoice_number) {
                if ($invoice_number) {
                    $query->where('invoice_number', 'like', '%' . $invoice_number . '%');//查询发票号
                }
            })
            ->when($cancel_reason, function ($query) use ($cancel_reason) {
                if ($cancel_reason) {
                    $query->where('cancel_reason', 'like', '%' . $cancel_reason . '%');//查询撤单理由
                }
            })
            ->when($number, function ($query) use ($number) {
                $query->whereHas('car', function ($query2) use ($number) {
                    if ($number) {
                        $query2->where('number', 'like', '%' . $number . '%');            //车牌号
                    }
                });
            })
            ->when($reality_start, function ($query) use ($reality_start) {
                $query->whereHas('distance', function ($query2) use ($reality_start) {
                    if ($reality_start) {
                        $query2->where('reality_start', 'like', '%' . $reality_start . '%');            //查询实际起始地
                    }
                });
            })
            ->when($reality_end, function ($query) use ($reality_end) {
                $query->whereHas('distance', function ($query2) use ($reality_end) {
                    if ($reality_end) {
                        $query2->where('reality_end', 'like', '%' . $reality_end . '%');              //查询实际终点
                    }
                });
            })
            ->when($book_time, function ($query) use ($book_time) {
                $query->whereHas('distance', function ($query2) use ($book_time) {
                    if ($book_time) {
                        $list = explode(',', $book_time);
                        $query2->whereBetween('book_time', [$list[0], $list[1]]);    //查询预约时间
                    }
                });
            })
            ->when($reality_start_time, function ($query) use ($reality_start_time) {
                $query->whereHas('distance', function ($query2) use ($reality_start_time) {
                    if ($reality_start_time) {
                        $list = explode(',', $reality_start_time);
                        $query2->whereBetween('reality_start_time', [$list[0], $list[1]]);    //查询实际上车时间
                    }
                });
            })
            ->when($c_name, function ($query) use ($c_name) {
                $query->whereHas('corporation', function ($query2) use ($c_name) {
                    if ($c_name) {
                        $query2->where('name', 'like', '%' . $c_name . '%');             //查询服务机构
                    }
                });
            })
            ->when($nick_name, function ($query) use ($nick_name) {
                $query->whereHas('passenger', function ($query2) use ($nick_name) {
                    if ($nick_name) {
                        $query2->where('nick_name', 'like', '%' . $nick_name . '%');             //查询下单用户昵称
                    }
                });
            })
            ->when($mobile, function ($query) use ($mobile) {
                $query->whereHas('driver', function ($query2) use ($mobile) {
                    if ($mobile) {
                        $query2->where('phone', 'like', '%' . $mobile . '%');            //查询司机电话
                    }
                });
            })
            ->when($real_name, function ($query) use ($real_name) {
                $query->whereHas('driver', function ($query2) use ($real_name) {
                    if ($real_name) {
                        $query2->where('real_name', 'like', '%' . $real_name . '%');            //查询司机姓名
                    }
                });
            })
            ->when($passenger, function ($query) use ($passenger) {
                $query->whereHas('passenger', function ($query2) use ($passenger) {
                    if ($passenger) {
                        $query2->where('phone', 'like', '%' . $passenger . '%');            //查询用户手机号
                    }
                });
            })
            ->latest()
            ->orderBy('id', 'desc')
            ->where('type', $types)
            ->paginate($pageSize);
        foreach ($list as $key => $item) {
            $arr = array('2', '3', '4', '5', '6');
            $aa = in_array($item['status'], $arr);
            if ($aa) {
                if (empty($item['distance']['reality_start'])) $item['distance']['reality_start'] = $item['distance']['book_start'];
                if (empty($item['distance']['reality_end'])) $item['distance']['reality_end'] = $item['distance']['book_end'];
            }
        }
        return $list;
    }

    /**
     * 订单导出
     * @param int $companyId 公司ID
     * @param int $type 订单类型
     * @param int $pageSize
     * @return LengthAwarePaginator
     * @Author 姿势就是力量
     */
    public function orderExcel($companyIds, int $status, int $type_name, $type, $passenger, string $order_sn, string $number, string $reality_start, string $reality_end, string $created_at, string $book_time, string $end_time, string $reality_start_time, string $should_price, string $discount_price, string $km, string $minute, string $c_name, string $nick_name, string $mobile, string $real_name, string $driver_money, string $surplus_profit, string $invoice_number, string $cancel_reason, string $types)
    {

        return $this->model
            ->when($type, function ($query) use ($type) {
                $query->where('service_id', $type);
            })
            ->with([
                'corporation:id,name',
                'driver:id,real_name,phone',
                'passenger:id,name,phone,nick_name',
                'car:id,number',
                'distance:id,order_id,book_time,reality_start_time,reality_start,reality_end',
                'service_type:id,name',
            ])
            ->when($order_sn, function ($query) use ($order_sn) {
                if ($order_sn) {
                    $query->where('order_sn', 'like', '%' . $order_sn . '%'); //查询订单号
                }
            })
            ->when($status, function ($query) use ($status) {
                if ($status) {
                    $query->where('status', 'like', '%' . $status . '%');       //订单状态
                }
            })
            ->when($type_name, function ($query) use ($type_name) {
                if ($type_name) {
                    $query->where('service_type_id', 'like', '%' . $type_name . '%'); //业务类型
                }
            })
            ->when($created_at, function ($query) use ($created_at) {
                if ($created_at) {
                    $list = explode(',', $created_at);
                    $query->whereBetween('created_at', [$list[0], $list[1]]); //下单时间
                }
            })
            ->when($end_time, function ($query) use ($end_time) {
                if ($end_time) {
                    $list = explode(',', $end_time);
                    $query->whereBetween('end_time', [$list[0], $list[1]]);   //查询结束时间
                }
            })
            ->when($should_price, function ($query) use ($should_price) {
                if ($should_price) {
                    $query->where('should_price', 'like', '%' . $should_price . '%');   //查询应收金额
                }
            })
            ->when($discount_price, function ($query) use ($discount_price) {
                if ($discount_price) {
                    $query->where('discount_price', 'like', '%' . $discount_price . '%');   //查询优惠金额
                }
            })
            ->when($km, function ($query) use ($km) {
                if ($km) {
                    $query->where('km', 'like', '%' . $km . '%');//查询服务里程
                }
            })
            ->when($minute, function ($query) use ($minute) {
                if ($minute) {
                    $query->where('minute', 'like', '%' . $minute . '%');//查询总服务时间
                }
            })
            ->when($driver_money, function ($query) use ($driver_money) {
                if ($driver_money) {
                    $query->where('driver_money', 'like', '%' . $driver_money . '%');//查询司机应得
                }
            })
            ->when($surplus_profit, function ($query) use ($surplus_profit) {
                if ($surplus_profit) {
                    $query->where('surplus_profit', 'like', '%' . $surplus_profit . '%');//查询剩余利润
                }
            })
            ->when($invoice_number, function ($query) use ($invoice_number) {
                if ($invoice_number) {
                    $query->where('invoice_number', 'like', '%' . $invoice_number . '%');//查询发票号
                }
            })
            ->when($cancel_reason, function ($query) use ($cancel_reason) {
                if ($cancel_reason) {
                    $query->where('cancel_reason', 'like', '%' . $cancel_reason . '%');//查询撤单理由
                }
            })
            ->when($number, function ($query) use ($number) {
                $query->whereHas('car', function ($query2) use ($number) {
                    if ($number) {
                        $query2->where('number', 'like', '%' . $number . '%');            //车牌号
                    }
                });
            })
            ->when($reality_start, function ($query) use ($reality_start) {
                $query->whereHas('distance', function ($query2) use ($reality_start) {
                    if ($reality_start) {
                        $query2->where('reality_start', 'like', '%' . $reality_start . '%');            //查询实际起始地
                    }
                });
            })
            ->when($reality_end, function ($query) use ($reality_end) {
                $query->whereHas('distance', function ($query2) use ($reality_end) {
                    if ($reality_end) {
                        $query2->where('reality_end', 'like', '%' . $reality_end . '%');              //查询实际终点
                    }
                });
            })
            ->when($book_time, function ($query) use ($book_time) {
                $query->whereHas('distance', function ($query2) use ($book_time) {
                    if ($book_time) {
                        $list = explode(',', $book_time);
                        $query2->whereBetween('book_time', [$list[0], $list[1]]);    //查询预约时间
                    }
                });
            })
            ->when($reality_start_time, function ($query) use ($reality_start_time) {
                $query->whereHas('distance', function ($query2) use ($reality_start_time) {
                    if ($reality_start_time) {
                        $list = explode(',', $reality_start_time);
                        $query2->whereBetween('reality_start_time', [$list[0], $list[1]]);    //查询实际上车时间
                    }
                });
            })
            ->when($c_name, function ($query) use ($c_name) {
                $query->whereHas('corporation', function ($query2) use ($c_name) {
                    if ($c_name) {
                        $query2->where('name', 'like', '%' . $c_name . '%');             //查询服务机构
                    }
                });
            })
            ->when($nick_name, function ($query) use ($nick_name) {
                $query->whereHas('passenger', function ($query2) use ($nick_name) {
                    if ($nick_name) {
                        $query2->where('nick_name', 'like', '%' . $nick_name . '%');             //查询下单用户昵称
                    }
                });
            })
            ->when($mobile, function ($query) use ($mobile) {
                $query->whereHas('driver', function ($query2) use ($mobile) {
                    if ($mobile) {
                        $query2->where('phone', 'like', '%' . $mobile . '%');            //查询司机电话
                    }
                });
            })
            ->when($real_name, function ($query) use ($real_name) {
                $query->whereHas('driver', function ($query2) use ($real_name) {
                    if ($real_name) {
                        $query2->where('real_name', 'like', '%' . $real_name . '%');            //查询司机姓名
                    }
                });
            })
            ->when($passenger, function ($query) use ($passenger) {
                $query->whereHas('passenger', function ($query2) use ($passenger) {
                    if ($passenger) {
                        $query2->where('phone', 'like', '%' . $passenger . '%');            //查询用户手机号
                    }
                });
            })
            ->latest()
            ->where('types', $types)
            ->where('status', '<>', '0')
            ->whereIn('company_id', $companyIds)
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();

    }


    /**
     * 订单详情
     * @param int $id 订单ID
     * @return mixed
     * @Author 姿势就是力量
     */
    public function getFind(int $id)
    {

        $info = $this->model
            ->with([
                'service_type:id,name',
                'corporation:id,name',
                'passenger:id,name,phone,nick_name',
                'driver:id,real_name,phone',
                'distance',
                'flow:id,order_id,created_at,price,pay_sn,type',
            ])
            ->where('id', $id)
            ->first();
        if (empty($info->service_type)) {
            $res_arrs = ServiceType::query()->whereIn('id', explode(',', $info->call_service_type_id))->get('name')->toArray();
            $res_arr = [];
            array_walk_recursive($res_arrs, function ($k) use (&$res_arr) {
                $res_arr[] = $k;
            });
            $info->service_types = implode(',', $res_arr);
        }
        $arr = array('2', '3', '4', '5', '6');
        $aa = in_array($info->status, $arr);
        if ($aa) {
            if (empty($info->distance->reality_start)) $info->distance->reality_start = $info->distance->book_start;
            if (empty($info->distance->reality_end)) $info->distance->reality_end = $info->distance->book_end;
        }

        return $info;
    }

    /**
     * 保存信息
     * @param array $params
     * @return Orders|Collection|Model
     * @Author 姿势就是力量
     */
    public function saveData(array $params)
    {
        if (!empty($params['id'])) {
            $model = $this->find($params['id']);
        } else {
            $model = $this->model;
        }

        foreach ($params as $key => $value) {
            $model->{$key} = $value;
        }
        $model->save();

        return $model;
    }


    /**
     * 统计订单
     * @param array $condition
     * @return mixed
     * @Author 姿势就是力量
     */
    public function countBy(array $condition)
    {
        return $this->model->where($condition)->count() ?? 0;
    }


    /**
     * 统计订单数据
     * @param array $condition 条件
     * @param string $field 统计字段
     * @return mixed
     * @Author 姿势就是力量
     */
    public function sumBy(array $condition, string $field)
    {
        return $this->model->where($condition)->sum($field) ?? 0;
    }

}
